<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宿舍管理系统 - 个人中心</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 60px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #007bff;
            color: white;
            border-radius: 15px 15px 0 0 !important;
        }
        .nav-link.active {
            background-color: #007bff !important;
            color: white !important;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
        <div class="container">
            <a class="navbar-brand" href="#">宿舍管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#profile">个人信息</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#preferences">偏好设置</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#roommates">室友匹配</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3" id="userInfo">
                        <!-- 用户信息将通过JavaScript填充 -->
                    </span>
                    <button class="btn btn-light" onclick="logout()">退出登录</button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container">
        <!-- 个人信息卡片 -->
        <div class="card" id="profile">
            <div class="card-header">
                <h5 class="card-title mb-0">个人信息</h5>
            </div>
            <div class="card-body">
                <form id="profileForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">学号</label>
                                <input type="text" class="form-control" id="studentId" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">姓名</label>
                                <input type="text" class="form-control" id="name" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">邮箱</label>
                                <input type="email" class="form-control" id="email">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">专业</label>
                                <input type="text" class="form-control" id="major">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">年级</label>
                                <select class="form-select" id="grade">
                                    <option value="1">大一</option>
                                    <option value="2">大二</option>
                                    <option value="3">大三</option>
                                    <option value="4">大四</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">保存修改</button>
                </form>
            </div>
        </div>

        <!-- 偏好设置卡片 -->
        <div class="card" id="preferences">
            <div class="card-header">
                <h5 class="card-title mb-0">偏好设置</h5>
            </div>
            <div class="card-body">
                <form id="preferencesForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">作息时间</label>
                                <select class="form-select" id="sleepingHabit" required>
                                    <option value="">请选择作息时间</option>
                                    <option value="EARLY">早睡早起</option>
                                    <option value="NORMAL">正常作息</option>
                                    <option value="LATE">晚睡晚起</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">卫生习惯</label>
                                <select class="form-select" id="cleanliness" required>
                                    <option value="">请选择卫生习惯</option>
                                    <option value="VERY_CLEAN">非常整洁</option>
                                    <option value="CLEAN">整洁</option>
                                    <option value="NORMAL">一般</option>
                                    <option value="CASUAL">随意</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">兴趣标签</label>
                        <div class="mb-2">
                            <select class="form-select mb-2" id="predefinedTags" multiple>
                                <option value="运动">运动</option>
                                <option value="音乐">音乐</option>
                                <option value="游戏">游戏</option>
                                <option value="阅读">阅读</option>
                                <option value="电影">电影</option>
                                <option value="旅行">旅行</option>
                                <option value="摄影">摄影</option>
                                <option value="美食">美食</option>
                            </select>
                        </div>
                        <div class="input-group">
                            <input type="text" class="form-control" id="customTag" placeholder="添加自定义兴趣标签">
                            <button class="btn btn-outline-primary" type="button" onclick="addCustomTag()">添加</button>
                        </div>
                        <div class="mt-2" id="selectedTags">
                            <!-- 已选择的标签将在这里显示 -->
                        </div>
                        <small class="text-muted">最多可选择8个兴趣标签</small>
                    </div>
                    <button type="submit" class="btn btn-primary">保存偏好</button>
                </form>
            </div>
        </div>

        <!-- 室友匹配卡片 -->
        <div class="card" id="roommates">
            <div class="card-header">
                <h5 class="card-title mb-0">室友匹配</h5>
            </div>
            <div class="card-body">
                <div class="text-center mb-4">
                    <button class="btn btn-primary" onclick="findMatches()">开始匹配</button>
                </div>
                <div id="matchResults" class="row">
                    <!-- 匹配结果将通过JavaScript填充 -->
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 检查登录状态
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = '/static/index.html';
        }

        // 加载个人信息
        async function loadProfile() {
            try {
                const response = await fetch('/students/me', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const data = result.data;  // 从响应中获取data字段
                    
                    // 更新导航栏的用户信息
                    document.getElementById('userInfo').textContent = `${data.student_id} - ${data.name}`;
                    
                    // 更新个人信息表单
                    document.getElementById('studentId').value = data.student_id || '';
                    document.getElementById('name').value = data.name || '';
                    document.getElementById('email').value = data.email || '';
                    document.getElementById('major').value = data.major || '';
                    if (data.grade) {
                        document.getElementById('grade').value = data.grade;
                    }
                    
                    console.log('个人信息加载成功:', data);
                } else {
                    const error = await response.json();
                    console.error('加载个人信息失败:', error);
                    alert('加载个人信息失败：' + (error.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载个人信息时发生错误:', error);
                alert('加载个人信息失败，请刷新页面重试');
            }
        }

        // 保存个人信息
        document.getElementById('profileForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            // 获取表单数据
            const major = document.getElementById('major').value.trim();
            const grade = document.getElementById('grade').value;
            const email = document.getElementById('email').value.trim();
            
            // 验证必填字段
            if (!major) {
                alert('请填写专业信息');
                return;
            }
            
            if (!grade) {
                alert('请选择年级');
                return;
            }
            
            if (!email) {
                alert('请填写邮箱');
                return;
            }
            
            const formData = {
                email: email,
                major: major,
                grade: parseInt(grade)
            };
            
            console.log('提交的个人信息:', formData);

            try {
                const response = await fetch('/students/me', {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const result = await response.json();
                
                if (response.ok) {
                    alert(result.message || '个人信息更新成功');
                    // 刷新显示的个人信息
                    loadProfile();
                } else {
                    console.error('更新失败:', result);
                    alert(result.message || '更新失败，请稍后重试');
                }
            } catch (error) {
                console.error('更新个人信息时发生错误:', error);
                alert('更新失败，请检查网络连接后重试');
            }
        });

        // 保存偏好设置
        document.getElementById('preferencesForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            // 验证必填字段
            const sleepingHabit = document.getElementById('sleepingHabit').value;
            const cleanliness = document.getElementById('cleanliness').value;
            const interestTags = Array.from(document.querySelectorAll('.tag-badge')).map(tag => tag.textContent.trim().replace(' ×', ''));
            
            if (!sleepingHabit || !cleanliness) {
                alert('请选择作息时间和卫生习惯');
                return;
            }
            
            if (interestTags.length === 0) {
                alert('请至少选择一个兴趣标签');
                return;
            }
            
            if (interestTags.length > 8) {
                alert('最多只能选择8个兴趣标签');
                return;
            }
            
            const formData = {
                sleeping_habit: sleepingHabit,
                cleanliness: cleanliness,
                interest_tags: interestTags
            };
            
            console.log('提交的偏好设置:', formData);

            try {
                const response = await fetch('/students/me/preferences', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(formData)
                });

                const result = await response.json();
                
                if (response.ok) {
                    alert(result.message || '偏好设置保存成功');
                    // 刷新显示的偏好设置
                    loadPreferences();
                } else {
                    console.error('保存失败:', result);
                    alert(result.message || '保存失败，请稍后重试');
                }
            } catch (error) {
                console.error('保存偏好设置时发生错误:', error);
                alert('保存失败，请检查网络连接后重试');
            }
        });

        // 查找匹配的室友
        async function findMatches() {
            try {
                const response = await fetch('/students/me/matches', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                const resultsContainer = document.getElementById('matchResults');
                
                if (response.ok) {
                    const matches = await response.json();
                    if (matches.length === 0) {
                        resultsContainer.innerHTML = `
                            <div class="col-12">
                                <div class="alert alert-info">
                                    暂时没有找到合适的匹配。请确保您已经：
                                    <ul>
                                        <li>设置了作息时间和卫生习惯</li>
                                        <li>选择了至少一个兴趣标签</li>
                                        <li>完善了个人基本信息</li>
                                    </ul>
                                </div>
                            </div>
                        `;
                        return;
                    }
                    
                    resultsContainer.innerHTML = matches.map(match => {
                        const details = match.match_details;
                        return `
                        <div class="col-md-4 mb-3">
                            <div class="card h-100">
                                <div class="card-body">
                                    <h5 class="card-title">${match.student.name}</h5>
                                    <div class="progress mb-2">
                                        <div class="progress-bar" role="progressbar" 
                                             style="width: ${match.score}%" 
                                             aria-valuenow="${match.score}" 
                                             aria-valuemin="0" 
                                             aria-valuemax="100">
                                            ${match.score.toFixed(1)}%
                                        </div>
                                    </div>
                                    <p class="card-text">
                                        <small class="d-block">作息匹配：${details.schedule_score}分</small>
                                        <small class="d-block">卫生匹配：${details.cleanliness_score}分</small>
                                        <small class="d-block">兴趣匹配：${details.interest_score}分</small>
                                        <small class="d-block">互选加分：${details.preference_score}分</small>
                                        <small class="d-block">专业：${match.student.major || '未设置'}</small>
                                        <small class="d-block">共同兴趣：${match.common_interests.length > 0 ? match.common_interests.join(', ') : '无'}</small>
                                    </p>
                                    <button class="btn btn-sm btn-outline-primary" onclick="requestRoommate('${match.student.student_id}')">
                                        申请成为室友
                                    </button>
                                </div>
                            </div>
                        </div>
                    `}).join('');
                } else {
                    const errorData = await response.json();
                    resultsContainer.innerHTML = `
                        <div class="col-12">
                            <div class="alert alert-warning">
                                ${errorData.detail || '获取匹配结果失败，请确保您已完善个人信息和偏好设置'}
                                <hr>
                                <p class="mb-0">请检查以下内容：</p>
                                <ul class="mb-0">
                                    <li>在"个人信息"中填写专业和年级</li>
                                    <li>在"偏好设置"中选择作息时间和卫生习惯</li>
                                    <li>在"偏好设置"中至少选择一个兴趣标签</li>
                                </ul>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Error finding matches:', error);
                document.getElementById('matchResults').innerHTML = `
                    <div class="col-12">
                        <div class="alert alert-danger">
                            获取匹配结果时发生错误，请稍后重试
                        </div>
                    </div>
                `;
            }
        }

        // 申请成为室友
        async function requestRoommate(targetStudentId) {
            try {
                const response = await fetch(`/students/me/roommate-requests/${targetStudentId}`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    alert('申请已发送，等待对方确认');
                } else {
                    const errorData = await response.json();
                    alert(errorData.detail || '申请发送失败，请稍后重试');
                }
            } catch (error) {
                console.error('Error requesting roommate:', error);
                alert('申请发送失败，请稍后重试');
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            window.location.href = '/static/index.html';
        }

        // 页面加载完成后自动加载个人信息
        document.addEventListener('DOMContentLoaded', () => {
            loadProfile();
            loadPreferences();
        });

        // 兴趣标签相关函数
        const selectedTags = new Set();

        document.getElementById('predefinedTags').addEventListener('change', function(e) {
            const selectedOptions = Array.from(e.target.selectedOptions);
            selectedOptions.forEach(option => {
                addTag(option.value);
            });
            e.target.value = ''; // 重置选择
        });

        function addCustomTag() {
            const customTagInput = document.getElementById('customTag');
            const tagValue = customTagInput.value.trim();
            
            if (tagValue && addTag(tagValue)) {
                customTagInput.value = '';
            }
        }

        function addTag(tag) {
            if (selectedTags.size >= 8) {
                alert('最多只能选择8个兴趣标签');
                return false;
            }
            
            if (selectedTags.has(tag)) {
                alert('该标签已存在');
                return false;
            }

            selectedTags.add(tag);
            const tagsContainer = document.getElementById('selectedTags');
            const tagElement = document.createElement('span');
            tagElement.className = 'badge bg-primary me-2 mb-2 tag-badge';
            tagElement.style.cursor = 'pointer';
            tagElement.innerHTML = `${tag} <span class="ms-1">&times;</span>`;
            tagElement.onclick = () => {
                selectedTags.delete(tag);
                tagElement.remove();
            };
            tagsContainer.appendChild(tagElement);
            return true;
        }

        // 加载用户偏好设置
        async function loadPreferences() {
            try {
                const response = await fetch('/students/me/preferences', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('Loaded preferences:', data);
                    
                    // 清除现有标签
                    document.getElementById('selectedTags').innerHTML = '';
                    selectedTags.clear();
                    
                    // 设置作息和卫生习惯
                    if (data.sleeping_habit) {
                        document.getElementById('sleepingHabit').value = data.sleeping_habit;
                    }
                    if (data.cleanliness) {
                        document.getElementById('cleanliness').value = data.cleanliness;
                    }
                    
                    // 加载兴趣标签
                    if (data.interest_tags && Array.isArray(data.interest_tags)) {
                        data.interest_tags.forEach(tag => addTag(tag));
                    }
                } else {
                    console.error('Failed to load preferences:', response.status);
                }
            } catch (error) {
                console.error('Error loading preferences:', error);
            }
        }
    </script>
</body>
</html> 